package com.example.mode.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.mode.R;

import java.util.ArrayList;
import java.util.List;

public class ToDoListActivity extends AppCompatActivity {

    private EditText etNewTask;
    private Button btnAddTask;
    private ListView listView;
    private List<String> toDoList;
    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_to_do_list);

        etNewTask = findViewById(R.id.et);
        btnAddTask = findViewById(R.id.btn_add_task);
        listView = findViewById(R.id.to_do_list_view);

        toDoList = new ArrayList<>();
        toDoList.add("学习编程");
        toDoList.add("阅读书籍");
        toDoList.add("锻炼身体");
        toDoList.add("闭目养神");
        toDoList.add("练习写作");
        toDoList.add("学习英语");

        adapter = new ArrayAdapter<String>(this, R.layout.list_item_to_do, R.id.tv_task, toDoList) {
            @Override
            public View getView(int position, View convertView, android.view.ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                ImageButton btnDelete = view.findViewById(R.id.btn_delete_task);
                btnDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        toDoList.remove(position);
                        notifyDataSetChanged();
                    }
                });
                return view;
            }
        };

        listView.setAdapter(adapter);

        btnAddTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newTask = etNewTask.getText().toString().trim();
                if (!newTask.isEmpty()) {
                    toDoList.add(newTask);
                    adapter.notifyDataSetChanged();
                    etNewTask.setText("");
                }
            }
        });
    }
}